package server

import (
	"fmt"
	"github.com/cuiyuanxin/airuisi-admin/global"
	"github.com/cuiyuanxin/airuisi-admin/internal/router"
	"github.com/cuiyuanxin/airuisi-admin/pkg/server"
	"github.com/spf13/cobra"
	"github.com/zztroot/color"
	"log"
	"os"
)

var (
	configFile string
	ServerCmd  = &cobra.Command{
		Use:     "server",
		Short:   "Starting the service",
		Long:    "The default config configuration can be overridden by specifying the config file path, which is optional",
		Example: "airuisi service -c config/prod.yaml",
		PreRun: func(cmd *cobra.Command, args []string) {
			setup()
		},
		Run: func(cmd *cobra.Command, args []string) {
			run()
		},
	}
)

func init() {
	configFile = os.Getenv("APP_CONF")
	if configFile == "" {
		ServerCmd.PersistentFlags().StringVarP(&configFile, "config", "c", "config/prod.yaml", "config path, eg: -c config/prod.yaml")
	}
	if configFile == "" {
		configFile = "config/prod.yaml"
	}
	log.Println("Load the conf file:", configFile)
}

func setup() {
	// 初始化配置
	if err := setupSetting(configFile); err != nil {
		log.Panicf("setupSetting err: %s", color.Coat(err.Error(), color.Red))
	}
	log.Println(color.Coat("Configuration initialization successfully...", color.Green))
	// 初始化日志
	if err := setupLogger(global.Config); err != nil {
		log.Panicf("setupLogger err: %s", color.Coat(err.Error(), color.Red))
	}
	log.Println(color.Coat("Log initialization successfully...", color.Green))
	// 初始化数据库
	if err := setupDBEngine(global.Config); err != nil {
		log.Panicf("setupDBEngine err: %s", color.Coat(err.Error(), color.Red))
	}
	log.Println(color.Coat("Database initialization successfully...", color.Green))
	// 初始化Redis
	if err := setupRDBClient(global.Config); err != nil {
		log.Panicf("setupRDBClient err: %s", color.Coat(err.Error(), color.Red))
	}
	log.Println(color.Coat("Redis initialization successfully...", color.Green))
	// 初始化链路追踪
	if err := setupTracer(global.Config); err != nil {
		log.Panicf("setupTranslations err: %s", color.Coat(err.Error(), color.Red))
	}
	log.Println(color.Coat("Redis initialization successfully...", color.Green))

	//err = internal.SetupCasbin()
	//if err != nil {
	//	log.Fatalf("init.setupCasbin err：%s", color.Coat(err.Error(), color.Red))
	//}
}

func run() {
	// 初始化路由
	app := router.NewRouter(global.Config, global.Logger, global.Tracet)

	fmt.Println(color.Coat("Server run at:", color.Green))
	protocol := "http"
	if global.Config.Server.Ssl {
		protocol = "https"
	}
	fmt.Printf("- Local: %s://localhost:%s \r\n", protocol, global.Config.Server.Port)
	fmt.Printf("- Network: %s://%s:%s \r\n", protocol, global.Config.Server.Addr, global.Config.Server.Port)

	fmt.Println(color.Coat("Swagger docs run at:", color.Green))
	fmt.Printf("- Local: %s://localhost:%s/swagger/index.html \r\n", protocol, global.Config.Server.Port)
	fmt.Printf("- Network: %s://%s:%s/swagger/index.html \r\n", protocol, global.Config.Server.Addr, global.Config.Server.Port)

	server.Run(app, global.Config)
}
